﻿using Google.Protobuf.WellKnownTypes;
using System;
using System.Collections.Generic;
using System.Linq;
using TMPro;
using UnityEngine;
using UnityEngine.UI;


public class UserMomentsPanel : AppUI
{
    public Image followBtnBg;
    public Text followText;

    public UserBaseInfo userBaseInfo;

    public CommunityPanel communityPanel;

    public Color followActiveColor = Color.white;
    public Color followDisactiveColor = Color.white;

    UserMomentsInfo m_userMomentsInfo;

    public GameObject addMomentBtn;

    int m_FromUI;
    public const int FromUI_UserHomePanel = 1;
    public const int FromUI_MainPanel = 2;

    public override void Start()
    {
        base.Start();
    }
    public void Init(UserMomentsInfo userMomentsInfo,bool anim = true)
    {
        //m_FromUI = fromUI;

        m_userMomentsInfo = userMomentsInfo;

        FreshFollow(userMomentsInfo);

        userBaseInfo.Init(userMomentsInfo.user);

        communityPanel.Init(userMomentsInfo.moments.AsList(), anim);

        addMomentBtn.SetActive(userMomentsInfo.user.userId == MGame.instance.MUser.id);
    }

    void FreshFollow(UserMomentsInfo userMomentsInfo)
    {
        if (userMomentsInfo.user.userId == MGame.instance.MUser.id)
        {
            followBtnBg.gameObject.SetActive(false);
        }
        else
        {
            bool meFollow = MGame.instance.MUser.myFollows.Contains(userMomentsInfo.user.userId);

            if (meFollow)
            {
                followText.text = "已关注";
                followBtnBg.color = followDisactiveColor;
            }
            else
            {
                followText.text = "关注";
                followBtnBg.color = followActiveColor;
            }
        }
    }

    public void OnClickFollow()
    {
        bool meFollow = MGame.instance.MUser.myFollows.Contains(m_userMomentsInfo.user.userId);

        RequestServerController.instance.ReqFollow(MGame.instance.MUser.id,m_userMomentsInfo.user.userId, !meFollow, (ret) =>
        {
            //if (m_userMomentsInfo.user.followers == null)
            //    m_userMomentsInfo.user.followers = new List<long>();
            //var list = new List<long>(m_userMomentsInfo.user.followers);
            //list.Add(MGame.instance.MUser.id);
            //m_userMomentsInfo.user.followers = list;

            FreshFollow(m_userMomentsInfo);
        });
    }
    public void OnClickAddMoment()
    {
        UIController.instance.ShowUI<AddMomentPanel>();
    }

    public void Refresh(Moment moment)
    {
        if (m_userMomentsInfo != null)
        {
            UserMoment userMoment = new UserMoment(m_userMomentsInfo.user, moment);
            m_userMomentsInfo.moments = m_userMomentsInfo.moments.ArrayAdd(userMoment);
            this.Init(m_userMomentsInfo,false);
        }
    }
}
